# encoding=utf-8
# author:梁子龙
from datetime import datetime
from sqlalchemy import URL, DateTime, func
from sqlalchemy.orm import sessionmaker, scoped_session, DeclarativeBase, declared_attr
from sqlalchemy.orm import Mapped, mapped_column
from config import settings
from sqlalchemy import create_engine

url = URL(
    drivername=settings.DATABASE.DRIVER,
    username=settings.DATABASE.get("USERNAME", None),
    password=settings.DATABASE.get("PASSWORD", None),
    host=settings.DATABASE.get("HOST", None),
    port=settings.DATABASE.get("PORT", None),
    database=settings.DATABASE.get("NAME", None),
    query=settings.DATABASE.get("QUERY", None),

)
# echo 是否打印  future 最新的flask-sqlalchemy
engine = create_engine(url, echo=True, future=True, pool_size=10)
sm = sessionmaker(bind=engine, autoflush=True, autocommit=True)  # autoflush 自动刷新
sessionFactory = scoped_session(sm)  # sessionFactory工厂


class DBModelBase(DeclarativeBase):
    @declared_attr.directive
    def __table_name__(cls) -> str:
        return "t_" + cls.__name__.lower()

    __table_args__ = {"mysql_engine": "InnoDB"}
    __mapper_args__ = {"eager_defaults": True}

    id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
    create_time: Mapped[datetime] = mapped_column(DateTime, insert_default=func.now(), comment="创建时间")
    update_time: Mapped[datetime] = mapped_column(DateTime, insert_default=func.now(), onupdate=func.now,
                                                  comment="修改时间")
